package com.wl.shop.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wl.shop.dao.UserDao;
import com.wl.shop.entity.User;
import com.wl.shop.service.SystemService;
import com.wl.shop.service.UserService;
import com.wl.shop.utils.StringUtils;

@Service("userService")
@Transactional(readOnly=true)
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

	@Override
	public Page<User> listByParam(Page<User> page, Map<String,Object> map) {
		// TODO Auto-generated method stub
		List<User> userList =baseMapper.selectUserPage(page, map);
		page.setRecords(userList);
		return page;
	}
	
	public int getCount(EntityWrapper<User> wrapper){
		return baseMapper.selectCount(wrapper);
	}
	
	@Override
	public void saveOrUpdate(User user) {
		// TODO Auto-generated method stub
		if(StringUtils.isNoneBlank(user.getPassword())){
			entryptPassword(user);
		}
		if(StringUtils.isBlank(user.getId())){
			user.preInsert();
			insert(user);
		}else{
			user.preUpdate();
			updateById(user);
		}
	}
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SystemService.SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));
		byte[] hashPassword = Digests.sha1(user.getPassword().getBytes(), salt, SystemService.HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}
	
}
